'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  Button, 
  Card, 
  Typography, 
  Space, 
  message,
  Tag
} from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { CreateTicketRequest, ApiResponse, Ticket } from '@/types/ticket';
import { 
  TICKET_PRIORITY_OPTIONS, 
  TICKET_CATEGORY_OPTIONS,
  ASSIGNEE_OPTIONS 
} from '@/utils/constants';

const { Title } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const CreateTicketPage: React.FC = () => {
  const router = useRouter();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tags, setTags] = useState<string[]>([]);

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const requestData: CreateTicketRequest = {
        title: values.title,
        description: values.description,
        priority: values.priority,
        category: values.category,
        assignee: values.assignee,
        dueDate: values.dueDate ? values.dueDate.toISOString() : undefined,
        tags: tags.length > 0 ? tags : undefined,
      };

      const response = await fetch('/api/tickets', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });

      const result: ApiResponse<Ticket> = await response.json();

      if (result.success) {
        message.success('工单创建成功');
        router.push('/');
      } else {
        message.error(result.message || '创建工单失败');
      }
    } catch (error) {
      console.error('创建工单失败:', error);
      message.error('创建工单失败');
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    router.back();
  };

  const handleAddTag = (value: string) => {
    if (value && !tags.includes(value)) {
      setTags([...tags, value]);
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setTags(tags.filter(tag => tag !== tagToRemove));
  };

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
          style={{ marginRight: 16 }}
        >
          返回
        </Button>
        <Title level={3} style={{ margin: 0 }}>创建新工单</Title>
      </div>

      <Card className="create-form">
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            requiredMark="optional"
          >
            <Form.Item
              name="title"
              label="工单标题"
              rules={[
                { required: true, message: '请输入工单标题' },
                { max: 100, message: '标题不能超过100个字符' }
              ]}
            >
              <Input placeholder="请输入工单标题" size="large" />
            </Form.Item>

            <Form.Item
              name="description"
              label="工单描述"
              rules={[
                { required: true, message: '请输入工单描述' },
                { max: 1000, message: '描述不能超过1000个字符' }
              ]}
            >
              <TextArea 
                placeholder="请详细描述工单内容..." 
                rows={6}
                showCount
                maxLength={1000}
              />
            </Form.Item>

            <Form.Item
              name="priority"
              label="优先级"
              rules={[{ required: true, message: '请选择优先级' }]}
              initialValue="medium"
            >
              <Select placeholder="选择优先级" size="large">
                {TICKET_PRIORITY_OPTIONS.map(option => (
                  <Option key={option.value} value={option.value}>
                    <Tag color={option.color}>{option.label}</Tag>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="category"
              label="工单分类"
              rules={[{ required: true, message: '请选择工单分类' }]}
              initialValue="bug"
            >
              <Select placeholder="选择工单分类" size="large">
                {TICKET_CATEGORY_OPTIONS.map(option => (
                  <Option key={option.value} value={option.value}>
                    <Tag color={option.color}>{option.label}</Tag>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="assignee"
              label="指派给"
            >
              <Select 
                placeholder="选择处理人（可选）" 
                size="large"
                allowClear
              >
                {ASSIGNEE_OPTIONS.map(assignee => (
                  <Option key={assignee} value={assignee}>
                    {assignee}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="dueDate"
              label="截止日期"
            >
              <DatePicker 
                placeholder="选择截止日期（可选）"
                size="large"
                style={{ width: '100%' }}
                disabledDate={(current) => current && current < dayjs().startOf('day')}
              />
            </Form.Item>

            <Form.Item label="标签">
              <div style={{ marginBottom: 8 }}>
                <Input.Search
                  placeholder="输入标签并按回车添加"
                  enterButton="添加"
                  size="large"
                  onSearch={handleAddTag}
                />
              </div>
              {tags.length > 0 && (
                <div>
                  {tags.map(tag => (
                    <Tag
                      key={tag}
                      closable
                      onClose={() => handleRemoveTag(tag)}
                      style={{ marginBottom: 8 }}
                    >
                      {tag}
                    </Tag>
                  ))}
                </div>
              )}
            </Form.Item>

            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  icon={<SaveOutlined />}
                  size="large"
                >
                  创建工单
                </Button>
                <Button onClick={handleBack} size="large">
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
    </div>
  );
};

export default CreateTicketPage; 